import { verifyToken } from '../utils/jwt.js';
import { query } from '../config/db.js';
import logger from '../config/logger.js';

/**
 * 认证中间件，用于验证JWT令牌
 */
const auth = async (req, res, next) => {
  console.log('auth 中间件');
  try {
    
    // const token = req.headers.authorization?.split(' ')[1];
    // if (!token) {
    //   return res.status(401).json({
    //     message: '需要认证'
    //   });
    // }

    const { token } = req.headers;
    // console.log('token:', token)
    if (!token) {
      console.log('token 不存在')
      return res.status(401).json({
        code: 401,
        message: '未提供认证令牌，请先登录获取令牌'
      });
    }

    const decoded = verifyToken(token);
    req.user = decoded;
    next();
  } catch (error) {
    logger.error('认证错误:', error);
    return res.status(401).json({
      code: 401,
      message: '无效或过期的令牌'
    });
  }
};

/**
 * 权限中间件，检查用户是否拥有所需权限
 * @param {string} permission - 所需权限名称
 */
const hasPermission = (permission) => async (req, res, next) => {
  // console.log('所需权限:', permission);
  // console.log('请求参数params:', req.params);
  // console.log('请求参数query:', req.query);
  // console.log('请求参数body:', req.body);
  // console.log('请求参数user:', req.user);


  try {
    const userId = req.user.id;

    // 检查用户是否拥有所需权限
    const result = await query(
      `
        SELECT p.name
        FROM permissions p
        JOIN user_permissions up ON p.id = up.permission_id
        WHERE up.user_id = ? AND p.name = ?
      `,
      [userId, permission]
    );
    // console.log('用户 ID:', userId, '用户权限:', result)
    if (result.rows.length === 0) {
      return res.status(403).json({
        message: `权限拒绝: ${permission}`
      });
    }

    next();
  } catch (error) {
    logger.error('权限检查错误:', error);
    return res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

export { auth, hasPermission };